<template>
  <view class="home-container">
    <!-- 推广横幅 -->
    <view class="promotion-banner">
      <u-swiper :list="bannerList" height="400" imgMode="aspectFit"></u-swiper>
    </view>

    <!-- Tab切换栏 -->
    <view class="tab-bar">
      <view class="tab-item" :class="{ active: activeTab === 'city' }" @click="switchTab('city')">
        城际线路
      </view>
      <view class="tab-item" :class="{ active: activeTab === 'rural' }" @click="switchTab('rural')">
        城乡线路
      </view>
    </view>
    <!-- 城际线路内容 v-if="activeTab === 'city'" -->
    <view class="tab-content">
      <view class="left-picker">
        <view style="flex: 1" v-if="isChangeLine">
          <view style="position: relative;">
            <view class="picker" :class="{ locationName: selectedStartLocation.name }"
              @click="showLocationPicker('departure')">{{ selectedStartLocation.name || '请选择出发地' }}</view>
          </view>
          <view>
            <view class="picker counties" :class="{ locationName: selectedEndLocation.name }"
              @click="showLocationPicker('destination')">{{ selectedEndLocation.name || '请选择目的地' }}</view>
          </view>
        </view>

        <view style="flex: 1" v-if="!isChangeLine">
          <view style="position: relative;">
            <view class="picker" :class="{ locationName: selectedStartLocation.name }"
              @click="showLocationPicker('departure')">{{ selectedStartLocation.name || '请选择目的地' }}</view>
          </view>
          <view>
            <view class="picker counties" :class="{ locationName: selectedEndLocation.name }"
              @click="showLocationPicker('destination')">{{ selectedEndLocation.name || '请选择出发地' }}</view>
          </view>
        </view>
        <view class="picker-change-icon" @click="changeLine">
          <image src="/static/home/change-icon.png" class="change-icon"></image>
        </view>
      </view>
      <button class="query-btn" @click="queryOwner">查询车主</button>
    </view>
    <!-- 我的行程 ?sid=${this.selectedStartLocation.id}& -->
    <view class="my-trip" v-if="userInfo.is_car_owner == 0 && isLoginFlag && myTrips.length > 0"
      v-for="(item, index) in myTrips" :key="index"
      @click="navigateTo(`/pages/personalCenter/trip/tripDetails?id=${item.id}`)">
      <view class="section-title">我的行程</view>
      <view class="trip-card">
        <view class="trip-header">
          <view class="city">
            <image src="/static/home/position.png" class="icon"></image>
            <text>{{ item.start_name }}</text>
          </view>
          <view class="status">
            <text class="status-text">{{ item.status_text }}</text>
            <image src="/static/home/line.png" class="status-line-icon"></image>
          </view>
          <view class="city">
            <image src="/static/home/position.png" class="icon"></image>
            <text>{{ item.end_name }}</text>
          </view>
        </view>

        <view class="trip-info">
          <view class="info-top-item">
            <view class="info-item">
              <image src="/static/home/time-icon.png" class="icon"></image>
              <text class="info-text">{{ item.start_time }}</text>
            </view>
            <view class="info-item">
              <image src="/static/home/location-icon.png" class="icon"></image>
              <text class="info-text">{{ item.carOwnerName }} {{ item.carOwnerPhone }}</text>
            </view>
          </view>
          <view class="info-item">
            <view class="info-item">
              <text class="info-label">上车点</text>
              <text class="info-text">{{ item.boarding_location }}</text>
            </view>
          </view>
        </view>

        <view class="action-buttons">
          <view class="share-btn" @click.stop="showShare(item)">
            <image src="/static/home/share-icon.png" class="share-icon"></image>
            <text>分享行程</text>
          </view>
          <!-- carOwnerUid -->
          <view class="chat-btn"
            @click.stop="onClickChat(item)">
            <image src="/static/home/chat-icon.png" class="chat-icon"></image>
            <text>位置聊天</text>
          </view>
        </view>
      </view>
    </view>
    <empty-data class="my-trip" v-if="userInfo.is_car_owner == 0 && !isLoginFlag && myTrips.length == 0"
      defaultText="暂无数据" />
    <!-- 常用路线 -->
    <view class="recommended-routes"  v-if="isLoginFlag">
      <view class="section-title">常用路线</view>
      <view class="route-list" v-if="commonlyUsedLine.length > 0">
        <view class="route-item" v-for="(item, index) in commonlyUsedLine" :key="index" @click="handleTo(item)">
          <view class="route-name">{{ item.start_name }}-{{ item.end_name }}</view>
          <view class="route-price">{{ item.count }}</view>
        </view>
      </view>
      <empty-data v-else defaultText="暂无数据" />
    </view>
    <!-- 推荐路线 -->
    <view class="recommended-routes">
      <view class="section-title"">推荐路线</view>
      <view class=" route-list" v-if="recommendLine.length > 0">
        <view class="route-item" v-for="(item, index) in recommendLine" :key="index" @click="handleTo(item)">
          <view class="route-name">{{ item.start_name }}-{{ item.end_name }}</view>
          <view class="route-price">{{ item.count }}</view>
        </view>
      </view>
      <empty-data v-else defaultText="暂无数据" />
    </view>
    <!-- <view class="promotion-banner-bottom">
      <image class="banner" src="/static/home/bto-banner.png"></image>
    </view> -->

    <packs-popup :visible.sync="showPopup" :couponsData="indexCoupons" @update:visible="updateVisible"
      @update:data="viewAllPopup" />

	<share-flex-vue></share-flex-vue>
	
	<packsPopup2></packsPopup2>
	
	<!-- 分享引导蒙层 -->
	<ShareGuideVue :show.sync="showGuide" :shareData="shareData"></ShareGuideVue>
  </view>
</template>

<script>
	import shareFlexVue from '../../components/shareFlex.vue';
import packsPopup from '../common/packsPopup.vue'
import packsPopup2 from '../common/packsPopup2.vue'
import { isLoggedIn } from '@/utils/auth'
import { formatDateTime } from '@/utils/dateTimeFormatter.js';
import ShareGuideVue from '../common/ShareGuide.vue';
export default {
  components: {
    packsPopup,shareFlexVue,ShareGuideVue,packsPopup2
 
  },
  data() {
    return {
		shareData: {
			title: '拼车出行，绿色环保',
			desc: '发现更多拼车路线，省钱又环保',
			link: '',
			imageUrl: 'https://carpool.mszcdf.cn/static/logo.png'
		},
      showGuide: false,
      selectedStartLocation: {},
      selectedEndLocation: {},
      isChangeLine: true,
      showPopup: false,
      activeTab: "city", // 默认激活城际线路
      bannerList: [],
      commonlyUsedLine: [],
      recommendLine: [],
      page: 1,
      size: 20,
      userInfo: null,
      myTrips: [],
      indexCoupons: [],
      isLoginFlag: false,
 
      safeCenterPosition: { x: 0, y: 0 }, // 安全中心按钮位置
      touchStartX: 0,
      touchStartY: 0,
      touchEndX: 0,
      touchEndY: 0,
    };
  },

  onLoad() {
    this.isLoginFlag = isLoggedIn()
    // this.initSafeCenterPosition()
	
	this.getLoacSelect()
  },
  onShow(options) {
    this.userInfo = uni.getStorageSync('userInfo')
    this.getMyPromotion()
    this.getMyRecommendLine()
    this.getCommonUseLine()

    // 检查优惠券大礼包弹窗 显隐
    if (this.userInfo && this.userInfo.is_gift != 1) {
      this.getCouponsList();
    }
    // 0 乘客 1 车主
    if (this.userInfo.is_car_owner == 1) {
      this.getMotoristsTrip()
    } else {
      this.getPassengerTrip()
    }
  },

  methods: {
	  getLoacSelect(){
		  const data = uni.getStorageSync(this.activeTab+'loc')
		  
		  if(data.selectedStartLocation){
		  		this.currenPositionType = 'departure'
		  		this.setLocation(data.selectedStartLocation)
		  }else{
			  this.selectedStartLocation = {}
		  }
		  
		  if(data.selectedEndLocation){
		  		this.currenPositionType = ''
		  		this.setLocation(data.selectedEndLocation)
		  }else{
			  this.selectedEndLocation = {}
		  }
	  },
	  onClickChat(item){
		  console.log(1111112,item)
		  
		  
		  uni.setStorageSync('lineOrders',[{
			  ...item,
			  phone:item.carOwnerPhone,
			  uid:item.carOwnerUid
		  }]);
		  
		  this.navigateTo('/pages/personalCenter/trip/locationChat?lid=' + item.line_id + '&carOwnerUid=' + item.carOwnerUid + '&type=' + 'passenger' + '&carOwnerName=' + item.carOwnerPhone)
	
	
	  },
    async getCouponsList() {
      let params = { status: 0 };
      try {
        const data = await this.$http.get("/h5/user/coupons", params);
        if (data.data.length > 0) {
          this.showPopup = true
        }
        this.indexCoupons = data.data || [];
      } catch (error) { }
    },
    // 选择的出发地 目的地
    setLocation(data) {
      if (this.currenPositionType === 'departure') {
        this.selectedStartLocation = data
      } else {
        this.selectedEndLocation = data
      }
	  
	  
	  
	  uni.setStorageSync(this.activeTab+'loc',{selectedStartLocation:this.selectedStartLocation,selectedEndLocation:this.selectedEndLocation})
	  
	  
    },
    showLocationPicker(type) {
      this.currenPositionType = type
      uni.navigateTo({
        url: `/pages/home/location-picker?type=${type}&activeTab=${this.activeTab}`
      });
    },
    // 乘客行程
    async getPassengerTrip() {
      if (!this.userInfo.id) {
        return
      }
      let params = {
        page: this.page,
        size: this.size,
        status: 0,
      }
      try {
        const res = await this.$http.get('/h5/user/trip/passenger', params)
        this.myTrips = res.data.list || []
        this.myTrips && this.myTrips.forEach(item => {
          item.start_time = formatDateTime(item.start_time)
        })

      } catch (error) { }
    },
    // 车主行程
    async getMotoristsTrip() {
      let params = {
        page: this.page,
        size: this.size,
        status: 0,
      }
      try {
        const res = await this.$http.get('/h5/user/line/myLine', params)
        this.myTrips = res.data.list || []

      } catch (error) { }
    },
    // 轮播
    async getMyPromotion() {
      try {
        const data = await this.$http.get('/h5/home/carousel?ident=' + 1);
        this.bannerList = data.data && data.data.map(i => {
          return i.image_full
        })
      } catch (error) { }
    },
    changeLine() {
      this.isChangeLine = !this.isChangeLine;
      let startLocation = this.selectedStartLocation;
      let endLocation = this.selectedEndLocation;
      this.selectedStartLocation = endLocation;
      this.selectedEndLocation = startLocation;
    },
    // 常用线路
    async getCommonUseLine() {
      let userInfo = uni.getStorageSync('userInfo')
      if (!userInfo.id) {
        return
      }
      let params = {
        type: this.activeTab === 'city' ? 2 : 1,  // 类型：1=城乡线路，2=城际线路
        start_id: this.selectedStartLocation.id || '', // 出发地
        end_id: this.selectedEndLocation.id || '', // 目的地
      }
      const { type, start_id, end_id } = params
      try {
        const data = await this.$http.get(`/h5/line/commonUseLine?type=${type}&start_id=${start_id}&end_id=${end_id}`);
        this.commonlyUsedLine = data.data
      } catch (error) { }
    },

    // 推荐线路
    async getMyRecommendLine() {

      let params = {
        type: this.activeTab === 'city' ? 2 : 1, // 类型：1=城乡线路，2=城际线路
        start_id: this.selectedStartLocation.id || '', // 出发地
        end_id: this.selectedEndLocation.id || '', // 目的地
        uid: this.userInfo && this.userInfo.id || '',
      }
      const { type, start_id, end_id, uid } = params
      try {
        const data = await this.$http.get(`/h5/line/recommendLine?type=${type}&start_id=${start_id}&end_id=${end_id}&uid=${uid}`);
        this.recommendLine = data.data
      } catch (error) { }
    },
    updateVisible() {
      this.showPopup = false
    },
    viewAllPopup() {
      uni.navigateTo({
        url: '/pages/personalCenter/coupon/index',
      });
    },
    // 切换Tab
    switchTab(tab) {
      this.activeTab = tab;
      this.getMyPromotion() // 轮播
      this.getMyRecommendLine() // 推荐
      this.getCommonUseLine() // 常用
	  this.getLoacSelect()
    },
    handleTo(data) {
      uni.navigateTo({
        url: `/pages/home/queryOwners/index?sid=${data.start_id}&eid=${data.end_id}&sName=${data.start_name}&eName=${data.end_name}&type=${this.activeTab}`,
      });
    },
    // 查询车主
    queryOwner() {
      if (this.activeTab === "city") {
        if (!this.selectedStartLocation.name || !this.selectedEndLocation.name) {
          uni.showToast({
            title: "请选择到达市县",
            icon: "none",
          });
          return;
        }
        uni.navigateTo({
          url: `/pages/home/queryOwners/index?sid=${this.selectedStartLocation.id}&eid=${this.selectedEndLocation.id}&sName=${this.selectedStartLocation.name}&eName=${this.selectedEndLocation.name}&type=city`,
        });
      } else {
        if (!this.selectedStartLocation.name || !this.selectedEndLocation.name) {
          uni.showToast({
            title: "请选择到达城乡",
            icon: "none",
          });
          return;
        }
        uni.navigateTo({
          url: `/pages/home/queryOwners/index?sid=${this.selectedStartLocation.id}&eid=${this.selectedEndLocation.id}&sName=${this.selectedStartLocation.name}&eName=${this.selectedEndLocation.name}`,
        });
      }
    },
    //
    // 显示分享弹窗
    showShare(data) { 
      this.showGuide = true
    },
    // 导航到指定页面
    navigateTo(url) {
      uni.navigateTo({
        url: url,
      });
    },
 
  },
};
</script>

<style lang="scss" scoped>
/* 全局样式 */
page {
  background-color: #f5f5f5;
  font-family: Arial, sans-serif;
}

.home-container {
  /* padding: 10px; */
}

/* tab样式 */
.tab-bar {
  display: flex;
  height: 100rpx;
  line-height: 100rpx;
  text-align: center;
  border-bottom: 2rpx solid #eee;
  background: #ffffff;
  border-radius: 16rpx 16rpx 0 0;
  padding-top: 24rpx;
}

.tab-item {
  flex: 1;
  font-size: 32rpx;
  color: #999999;
  line-height: 84rpx;
  text-align: center;
}

.tab-item.active {
  position: relative;
  font-weight: 500;
  font-size: 36rpx;
  color: #ff7937;
  line-height: 84rpx;
}

.tab-item.active::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 144rpx;
  height: 8rpx;
  background-color: #ff7937;
  border-radius: 16rpx 16rpx 16rpx 16rpx;
}

.tab-content {
  background: #ffffff;
  margin-bottom: 40rpx;
}

.picker {
  padding: 26rpx 40rpx 26rpx 80rpx;
  border-bottom: 2rpx solid #eee;
  border-radius: 8rpx;

  font-weight: 400;
  font-size: 28rpx;
  color: #999999;
  line-height: 42rpx;
}

.left-picker {
  display: flex;
  align-items: center;
  padding-right: 40rpx;
  position: relative;
}

.picker::before {
  content: "";
  position: absolute;
  bottom: 42rpx;
  left: 7%;
  width: 16rpx;
  height: 16rpx;
  background: #00cfab;
  border-radius: 50%;
}

.counties::before {
  content: "";
  position: absolute;
  bottom: 42rpx;
  left: 6%;
  width: 16rpx;
  height: 16rpx;
  background: #ff7937;
  border-radius: 50%;
}

.locationName {
  font-weight: 500;
  font-size: 32rpx;
  color: #0b1f20;
  line-height: 48rpx;
}

.change-icon {
  width: 48rpx;
  height: 48rpx;
  margin-left: 36rpx;
}

.query-btn {
  height: 100rpx;
  line-height: 100rpx;
  margin-top: 40rpx;
  background: linear-gradient(90deg, #FF3F39 0%, #FF7937 100%);
  font-weight: 500;
  font-size: 36rpx;
  color: #ffffff;
  border-radius: 16rpx;
  margin: 20rpx 24rpx 0 24rpx;
}

/* 状态栏样式 */
.status-bar {
  display: flex;
  justify-content: space-between;
  padding: 5px 10px;
  font-size: 14px;
}

/* 推广横幅样式 */
.promotion-banner {}

.promotion-banner .banner {
  width: 750rpx;
  height: 400rpx;
}

.promotion-banner-bottom {
  display: flex;
  justify-content: center;
  margin-bottom: 40rpx;
}

.promotion-banner-bottom .banner {
  width: 700rpx;
  height: 240rpx;
}


/* 线路类型切换样式 */
.route-type {
  display: flex;
  margin: 15px 0;
}

.type-item {
  flex: 1;
  width: 128rpx;
  height: 48rpx;
  font-family: Source Han Sans CN, Source Han Sans CN;
  font-weight: 400;
  font-size: 32rpx;
  color: #999999;
  line-height: 48rpx;
  text-align: center;
  /* text-align: center;
  padding: 10px;
  border-bottom: 2px solid #ddd; */
}

.type-item.active {
  border-bottom: 2px solid #ff7937;
  color: #ff7937;
  font-weight: bold;
}

/* 我的行程样式 */
.my-trip {
  background: #ffffff;
  box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(0, 0, 0, 0.02);
  border-radius: 16rpx;
  margin: 0rpx 24rpx 20rpx 24rpx;
  padding: 24rpx 30rpx 34rpx 24rpx;
}

.trip-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 0 80rpx;
  margin-bottom: 54rpx;
}

.city {
  display: flex;
  align-items: center;
  font-weight: 500;
  font-size: 32rpx;
  color: #0b1f20;
  line-height: 48rpx;
}

.status {
  width: 88rpx;
  height: 32rpx;
  background: #ff7937;
  border-radius: 24rpx;
  text-align: center;
  line-height: 24rpx;
  position: relative;
}

.status-line-icon {
  width: 104rpx;
  height: 7rpx;
  /* position: absolute; */
}

.status-text {
  font-size: 20rpx;
  color: #ffffff;
}

.trip-info {
  margin-bottom: 20rpx;
  background: #f5f5f6;
  border-radius: 16rpx;
  padding: 30rpx 20rpx 28rpx 20rpx;
}

.info-top-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 18rpx;
}

.info-item {
  display: flex;
  align-items: center;
}

.icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 15rpx;
}

.info-label {
  font-size: 24rpx;
  color: #999999;
  line-height: 36rpx;
  margin-right: 24rpx;
}

.info-text {
  font-size: 28rpx;
  color: #0b1f20;
  line-height: 42rpx;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
}

.share-btn,
.chat-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 16rpx;
  font-size: 28rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.share-btn {
  background: #f5f5f6;
  margin-right: 20rpx;
  color: #666666;
}

.share-icon {
  width: 28rpx;
  height: 28rpx;
  margin-right: 8rpx;
}

.chat-icon {
  width: 25rpx;
  height: 25rpx;
  margin-right: 8rpx;
}

.chat-btn {
  background: #ffffff;
  border: 2rpx solid #ff7937;
  color: #ff7937;
}

.recommended-routes {
  background: #ffffff;
  box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(0, 0, 0, 0.02);
  border-radius: 16rpx;
  margin: 0rpx 24rpx 20rpx 24rpx;
  padding: 24rpx 30rpx 34rpx 24rpx;
}

.section-title {
  height: 52rpx;
  font-family: Source Han Sans CN, Source Han Sans CN;
  font-weight: 500;
  font-size: 34rpx;
  color: #0b1f20;
  line-height: 52rpx;
  text-align: left;
  font-style: normal;
  text-transform: none;
  padding-bottom: 24rpx;
  margin-bottom: 44rpx;
  border-bottom: 2rpx solid #eeeeee;
}

.trip-card {
  margin-bottom: 10px;
}

.trip-info .location {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.city {
  font-weight: bold;
}

.arrow {
  margin: 0 5px;
}

.time {
  color: #666;
  margin-bottom: 8px;
}

.driver,
.pickup {
  color: #666;
  font-size: 14px;
}

.time-status {
  display: flex;
  justify-content: space-between;
  color: #666;
}

.status {
  /* color: #ff0000; */
}

/* 常用路线样式 */
.route-title {
  width: 118rpx;
  height: 42rpx;
  font-family: Source Han Sans CN, Source Han Sans CN;
  font-weight: 400;
  font-size: 28rpx;
  color: #999999;
  line-height: 42rpx;
  text-align: left;
  font-style: normal;
  text-transform: none;
}

/* 推荐路线样式 */
.route-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin-top: 20rpx;
}

.route-item {
  background: #f5f5f6;
  border-radius: 16rpx;
  padding: 15px;
  width: 38%;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.route-name {
  font-family: Source Han Sans CN, Source Han Sans CN;
  font-weight: 400;
  font-size: 28rpx;
  color: #333333;
  line-height: 42rpx;
  text-align: left;
  font-style: normal;
  text-transform: none;
}

.route-price {
  font-family: Source Han Sans CN, Source Han Sans CN;
  font-weight: 400;
  font-size: 28rpx;
  color: #999999;
  line-height: 42rpx;
  text-align: right;
  font-style: normal;
  text-decoration-line: underline;
}

/* 底部导航样式 */
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
  box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.1);
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.nav-icon {
  font-size: 20px;
  margin-bottom: 3px;
}

.nav-text {
  font-size: 12px;
}
</style>
